﻿using AutoMapper;
using MediatR;
using PersonnelManagement.Application.Command.Clientcategory;
using PersonnelManagement.Domain.Dto;
using PersonnelManagement.Domain.PersonnelDomain;
using PersonnelManagement.Infrstructre.Interface;

namespace PersonnelManagement.Application.CommandHandler.ClientcategoryHandlers
{
    public class ClientcategoryShowCommandhandlers : IRequestHandler<ClientcategoryShowCommand, List<ClientCategoryDto>>
    {
        protected readonly IClientcategoryRepository repository;
        protected readonly IMapper mapper;

        public ClientcategoryShowCommandhandlers(IClientcategoryRepository repository, IMapper mapper)
        {
            this.repository = repository;
            this.mapper = mapper;
        }

        public async Task<List<ClientCategoryDto>> Handle(ClientcategoryShowCommand request, CancellationToken cancellationToken)
        {
            List<Clientcategory> categories = (await repository.Getall()).ToList();
            List<ClientCategoryDto> treeCategories = BuildTree(categories, request.id);
            return treeCategories;
        }
        static List<ClientCategoryDto> BuildTree(List<Clientcategory> categories, int parentId)
        {

            return categories
                .Where(c => c.CPid == parentId)
                .Select(c => new ClientCategoryDto
                {
                    value = c.CId,
                    label = c.CName,
                    children = BuildTree(categories, c.CId) // 递归构建子分类
                })
                .ToList();


        }
    }
}
